// PersistRegBase.cpp: implementation of the PersistRegBase class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "PersistRegBase.h"
#include "PersistentObject.h"
#include "ObjectPaternityMap.h"
#include "Tree.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

namespace PDMS
{
	using namespace PDMSFrame;
	namespace PDMSDBIF
	{
		IMPLEMENT_DYNAMIC_EX( PersisterIF, SmallObject );
		
		IMPLEMENT_DYNAMIC_EX( PersistRegBase, PersisterIF );
		IMPLEMENT_REGISTER( PersistRegBase, VersionOne );
		
		PersistRegBase::PersistRegBase()
		{
			
		}
		
		PersistRegBase::~PersistRegBase()
		{
			
		}
		
		UESoft::ErrorStatus PersistRegBase::CreatePaternity( Persistable* pObj )
		{
			ASSERT( GetDatabase() );
			DatabaseElement* pElement = GetDatabase()
				->GetDatabaseElement( _T("PaternityMap") );
			ASSERT( pElement );

			ASSERT( pElement->IsKindOf( UE_RUNTIME_CLASS( ObjectPaternityMap ) ) );
			ObjectPaternityMap* pMap = static_cast< ObjectPaternityMap* >( pElement );
			pMap->Open();
			pMap->NewRecord();
			pMap->SetID( pObj->Id().ObjectID() );
			pMap->SetParentID( pObj->OwnerId().ObjectID() );

			return UESoft::eOk;
		}
		
		UESoft::ErrorStatus PersistRegBase::ReadPaternity( Persistable* pObj )
		{
			ASSERT( GetDatabase() );
			DatabaseElement* pElement = GetDatabase()
				->GetDatabaseElement( _T("PaternityMap") );
			ASSERT( pElement );
			
			ASSERT( pElement->IsKindOf( UE_RUNTIME_CLASS( ObjectPaternityMap ) ) );
			ASSERT( pObj->IsKindOf( UE_RUNTIME_CLASS( UeDbObject ) ) );
			UeDbObject* pDbObj = static_cast< UeDbObject* >( pObj );
			ObjectPaternityMap* pMap = static_cast< ObjectPaternityMap* >( pElement );

			StdString strCondition;
			strCondition.Format( _T("ParentID = %ld"), pObj->Id().ObjectID() );

			UESoft::ErrorStatus es = pMap->Open( strCondition );
			if ( es != UESoft::eOk )
			{
				return es;
			}
			if ( pMap->IsNull() )
			{
				return pMap->Close();
			}

			pMap->MoveFirst();
			while( !pMap->IsEnd() )
			{
				pDbObj->AddSonId( UeObjectId( pObj->Id().EnviromentID(), pMap->GetID() ) );
				pMap->MoveNext();
			}
			return pMap->Close();
		}
	}
}